package filters;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import util.PReader;

import java.io.IOException;

@WebFilter("/api/*")
public class ApiFilter implements Filter {

    private final PReader PReader = new PReader();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        servletRequest.setCharacterEncoding("UTF-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if(request.getMethod().equals("POST") && request.getContentType().equals("application/json")) {
            String s = servletRequest.getReader() ==null ? "" : PReader.readJson(servletRequest.getReader());
            request.setAttribute("body",s);
            System.out.println("请求体是："+s);
        }
        servletResponse.setContentType("application/json");
        servletRequest.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
